package com.example.home_app.base.activity

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import com.android.frame.mvp.CommonBaseActivity
import com.android.util.threadPool.ThreadPoolManager
import com.example.home_app.databinding.ActivityLineChartBinding
import com.example.home_app.http.base.HistoricalData.Datastreams
import com.example.home_app.http.base.HistoricalData.HistoricalJsonRootBean
import com.example.home_app.http.base.onenetdevice.Data
import com.example.home_app.http.base.onenetdevice.GetRootBean
import com.example.home_app.util.Json
import com.example.home_app.util.MPAndroidChartUrils.ChartUtils
import com.example.home_app.util.SbParameter
import com.example.home_app.util.State
import com.example.home_app.util.Utils
import com.github.mikephil.charting.data.Entry
import com.gyf.immersionbar.ImmersionBar
import okhttp3.*
import java.io.IOException
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Created by dell on 2021/8/11.
 */
class LineChartActivity: CommonBaseActivity<ActivityLineChartBinding>() {
    private var okHttpClient: OkHttpClient? = null
    private var online: String? = null
    private var responseData: String? = null
    private var ID: String? = null
    private var create_time: Date? = null
    private var create_t: String? = null
    private var update_at: Date? = null
    private var update_t: String? = null
    private var endTime: String? = null
    private val list = ArrayList<Map<String, Any>>()
    private val tmp = ArrayList<Entry>()
    private val hum = ArrayList<Entry>()
    private var mWeakReference: WeakReference<LineChartActivity>? = null
    var map: Map<String, Any>? = null
    companion object {
        const val EXTRA_ID = "EXTRA_ID"
        const val EXTRA_MAME = "EXTRA_MAME"
        const val EXTRA_ONLINE = "EXTRA_ONLINE"
    }
    override fun handleView(savedInstanceState: Bundle?) {
        intView()
        initData()
        mWeakReference = WeakReference(this)

    }
    private fun intView(){

        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)

        /*温度湿度画图实例化*/
        ChartUtils.initChart(binding.chartTmp)
        ChartUtils.initChart(binding.chartHum)


    }
    override fun initListener() {

        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }
    private fun initData() {
        val bundle = intent.extras
        if (bundle != null) {
            ID = bundle.getString(EXTRA_ID)
            online = bundle.getString(EXTRA_ONLINE)
            binding.toolbar.title = bundle.getString(EXTRA_MAME)
        }
        val date = Date(System.currentTimeMillis())
        endTime = Utils.Endtime(Utils.dateToString(date, "yyyy-MM-ddHH:mm:ss"))
        binding.online.text = online
        //noinspection AlibabaUndefineMagicConstant
        if (online === "√") {
            //String o = String.valueOf(devices.get(i).getOnline());
            binding.online.setTextColor(Color.GREEN)
        } else {
            binding.online.setTextColor(Color.RED)
        }
        getInformation()
        getData()
        Handler(Looper.getMainLooper()).postDelayed({
            ChartUtils.notifyDataSetChanged(binding.chartTmp, tmp, ChartUtils.dayValue)
            ChartUtils.notifyDataSetChanged(binding.chartHum, hum, ChartUtils.dayValue)
        }, 200)

        ThreadPoolManager.instance.getScheduledThreadPool().scheduleWithFixedDelay(Runnable {
            dataTmp().let {
                ChartUtils.notifyDataSetChanged(binding.chartTmp,
                    it, ChartUtils.dayValue)
            }
            dataHum().let {
                ChartUtils.notifyDataSetChanged(binding.chartHum,
                    it, ChartUtils.dayValue)
            }
        }, 1, 5, TimeUnit.SECONDS)


    }
    private fun getInformation() {
        okHttpClient = OkHttpClient()
        val request = Request.Builder()
            .url("http://api.heclouds.com/devices/$ID/datastreams/")
            .header("api-key", State.ApiKey).build()
        val call = okHttpClient !!.newCall(request)
        call.enqueue(object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    responseData = response.body() !!.string()
                    val app: GetRootBean = Json.gson !!.fromJson(
                        responseData,
                        GetRootBean::class.java
                    )
                    val streams = app.getData() as List<Data>
                    update_at = streams[0].getUpdate_at()
                    create_time = streams[0].getCreate_time()

                    update_t = Utils.dateToString(update_at, "yyyy-MM-dd HH:mm:ss")
                    create_t = Utils.dateToString(create_time, "yyyy-MM-dd HH:mm:ss")
                    //noinspection AlibabaUndefineMagicConstant
                    for (i in 0..1) {
                        map = HashMap()
                        (map as HashMap<String, Any>)["current_value"] = streams[i].getCurrent_value() !!
                        (map as HashMap<String, Any>)["unit_symbol"] = streams[i].getUnit_symbol() !!
                        list.add(map as HashMap<String, Any>)
                    }
                    Handler(Looper.getMainLooper()).postDelayed({
                        if (State.DeviceIDs != ""){
                            binding.updatetime.text = update_t
                            binding.createTime.text = create_t
                            binding.temp.text = list[0]["current_value"].toString()
                            binding.hume.text = list[1]["current_value"].toString()
                        }
                    }, 200)

                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }

    private fun getData() {
        /**
         * 函数：sort
         * 时间排序方式，DESC：倒序，ASC：升序，默认为ASC
         */
        val request = Request.Builder()
            .url(
                "http://api.heclouds.com/devices/" + ID + "/datapoints?"
                        + "end=" + endTime + "&" +
                        "start=" + "2021-06-02T08:06:30" + "&" +
                        "sort=" + "DESC" + "&" +
                        "datastream_id=" + "temp,humi"
            )
            .header("api-key", State.ApiKey).build()
        val call = okHttpClient !!.newCall(request)
        call.enqueue(object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    val responseData = response.body() !!.string()
                    val historicalJsonRootBean = Json.gson !!.fromJson(
                        responseData,
                        HistoricalJsonRootBean::class.java
                    )
                    SbParameter.HISTORYLIST = historicalJsonRootBean.getData() !!.getCount()
                    if (historicalJsonRootBean.getData() !!.getCount() > 0) {
                        val data: List<Datastreams>? = historicalJsonRootBean.getData() !!
                            .getDatastreams()
                        val temp = data !![0].getDatapoints()
                        val hume = data [1].getDatapoints()

                        println(historicalJsonRootBean.getData() !!.getCount())

                        for (i in 0..6) {
                            val T = temp?.get(i)?.getValue() !!.toFloat()
                            val H = hume?.get(i)?.getValue() !!.toFloat()
                            tmp.add(i, Entry(i.toFloat(), T))
                            hum.add(i, Entry(i.toFloat(), H))
                        }
                        State.DHT11 = true

                    }

                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }

    //实现耗时操作的线程
    private var mBackgroundRunnable = Runnable {
        //----------模拟耗时的操作，开始---------------
        while (State.DHT11) {
            dataTmp().let {
                ChartUtils.notifyDataSetChanged(binding.chartTmp,
                    it, ChartUtils.dayValue)
            }
            dataHum().let {
                ChartUtils.notifyDataSetChanged(binding.chartHum,
                    it, ChartUtils.dayValue)
            }
            try {
                Thread.sleep(5000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }
        //----------模拟耗时的操作，结束---------------
    }


    private fun dataTmp(): List<Entry?> {
        tmp[0] = Entry(0F, tmp[1].y)
        tmp[1] = Entry(1F, tmp[2].y)
        tmp[2] = Entry(2F, tmp[3].y)
        tmp[3] = Entry(3F, tmp[4].y)
        tmp[4] = Entry(4F, tmp[5].y)
        tmp[5] = Entry(5F, tmp[6].y)
        if (tmp[6].y > 30) tmp[6] = Entry(6F, tmp[6].y - 5) else {
            tmp[6] = Entry(6F, tmp[6].y + 1)
        }
        return tmp
    }


    private fun dataHum(): List<Entry?> {
        hum[0] = Entry(0F, hum[1].y)
        hum[1] = Entry(1F, hum[2].y)
        hum[2] = Entry(2F, hum[3].y)
        hum[3] = Entry(3F, hum[4].y)
        hum[4] = Entry(4F, hum[5].y)
        hum[5] = Entry(5F, hum[6].y)
        hum[6] = Entry(6F, hum[6].y + 1)
        return hum
    }
    override fun onDestroy() {
        mWeakReference?.clear()
        ThreadPoolManager.instance.getFixedThreadPool().shutdownNow()
        ThreadPoolManager.instance.getScheduledThreadPool().shutdownNow()
        super.onDestroy()
    }
}